package com.uci.photogam;

/**
*
*/

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Vector;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Facebook;
import com.uci.photogam.facebook.BaseDialogListener;
import com.uci.photogam.facebook.BaseRequestListener;
import com.uci.photogam.facebook.FacebookAlbumList;
import com.uci.photogam.facebook.FacebookSSOActivity;
import com.uci.photogam.facebook.Utility;

/**
* The <code>PageAdapter</code> class is the fragment activity hosting the ViewPager
* @author mwho
*/
public class PageAdapter extends FragmentActivity{
	/** maintains the pager adapter*/
	private PagerAdapter mPagerAdapter;
	Bundle mybundle;

	private final String[] texts = { "Camera", "Gallery", "Share", "Facebook" };

	private static final int REQ_CODE_PICK_PICTURE = 0;
	private static final int REQ_CODE_TAKE_PICTURE = 2;
	private static final int REQ_CODE_PICK_PICTURE_ONLINE = 4; // facebook?

	private static final String IMG_SOURCE_CAMERA = "Camera";
	private static final String IMG_SOURCE_GALLERY = "Gallery";

	public static final int MEDIA_TYPE_IMAGE = 1;
	public static final int MEDIA_TYPE_VIDEO = 2;
	/** Create a file Uri for saving an image or video */

	private Uri imgUri;
	private String lastImgSelectedName;
	private String imageSource;
	private String galleryDir;

	private final static int CAMERA = 0;
	private final static int GALLERY = 1;
	private final static int SHARE = 2;
	private final static int FACEBOOK = 3;

	private Intent i;

	/* (non-Javadoc)
	 * @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.viewpager_layout);
        
        if (savedInstanceState == null) {
            // Do first time initialization -- add fragment.
            Fragment newFragment = new ReceiveResultFragment();
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.add(R.id.viewpager, newFragment).commit();
        }
        
		if(Utility.mFacebook == null)
			Utility.mFacebook = new Facebook("393520284025644");
		if(Utility.mAsyncRunner == null)
			Utility.mAsyncRunner = new AsyncFacebookRunner(Utility.mFacebook);

        
		//initialsie the pager
		this.initialisePaging();


	}

	
	@Override
	public void onSaveInstanceState(Bundle outState) {
	}

	  public void cameraBtnClick(View v)
      {
			// create Intent to take a picture and return control to the
			// calling application
			i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			// Alexis: I'm getting an null pointer exception at this
			// line when I select camera
			imgUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
			// create a file to save the image
			i.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
			// set the image file name
			// start the image capture Intent
			startActivityForResult(i, REQ_CODE_TAKE_PICTURE);
			

      }
	  
	  public void loginBtnClick(View v)
	  {
			if(!Utility.mFacebook.isSessionValid())
				Utility.mFacebook.authorize(PageAdapter.this, new String[]{"user_photos"}, new LogInDialogListener());	
			else
				V.toastMessage(getBaseContext(), "You are already logged in.");

	  }
	  
		class LogInDialogListener extends BaseDialogListener{

			public void onComplete(Bundle values) {
				//Utility.mAsyncRunner.request("me/albums", new AlbumRequestListener());
				V.toastMessage(getBaseContext(), "You have logged in.");
			}
		}

		public void logoutBtnClick(View v)
		{
			if(!Utility.mFacebook.isSessionValid())
				V.toastMessage(getBaseContext(), "You must log in first.");
			else
				Utility.mAsyncRunner.logout(getBaseContext(), new BaseRequestListener() {
					public void onComplete(String response, Object state) {
						V.toastMessage(getBaseContext(), "You have logged out.");
					}
				});

		}
		
		class AlbumRequestListener extends BaseRequestListener{

			public void onComplete(String response, Object state) {
				Intent intent = new Intent(getApplicationContext(), FacebookAlbumList.class);
				intent.putExtra("API_RESPONSE", response);
				startActivityForResult(intent, V.REQ_CODE_PICK_PICTURE_FB);
			}
		}

		public void albumBtnClick(View v)
		{
			if(!Utility.mFacebook.isSessionValid())
				V.toastMessage(getBaseContext(), "You must log in first.");
			else
				Utility.mAsyncRunner.request("me/albums", new AlbumRequestListener());

		}
		
		
	  public void galleryBtnClick(View v)
	  {
		// images on the SD card.
		i = new Intent(Intent.ACTION_PICK);
		i.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
		i.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    	Log.d("START RESULT", "HERE FROM ACTIVITY" );

		startActivityForResult(i, REQ_CODE_PICK_PICTURE);
    	Log.d("GOT RESULT", "HERE FROM ACTIVITY" );

	  }
	  
	  public void faceBkClick(View v)
	  {
		  albumBtnClick(v);
//		i = new Intent(PageAdapter.this,
//				FacebookSSOActivity.class);
//		startActivityForResult(i, REQ_CODE_PICK_PICTURE_ONLINE);
	  }
	  
	  
	  
	  
	  	@Override
		protected void onPause() {
			
	  		this.mPagerAdapter.saveState();
	  		super.onPause();
			
		}

	  	@Override
		protected void onResume() {
	  		
			super.onResume();
			Utility.mFacebook.extendAccessTokenIfNeeded(this, null);

		}
		

		private static Uri getOutputMediaFileUri(int type) {
			return Uri.fromFile(getOutputMediaFile(type));
		}

		/** Create a File for saving an image or video */
		private static File getOutputMediaFile(int type) {
			// To be safe, you should check that the SDCard is mounted
			// using Environment.getExternalStorageState() before doing this.
			File mediaStorageDir = new File(
					Environment
							.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
					"MyCameraApp");
			// This location works best if you want the created images to be shared
			// between applications and persist after your app has been uninstalled.
			// Create the storage directory if it does not exist
			if (!mediaStorageDir.exists()) {
				if (!mediaStorageDir.mkdirs()) {
					V.Log("MyCameraApp", "failed to create directory");
					return null;
				}
			}
			// Create a media file name
			String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
					.format(new Date());
			File mediaFile;
			if (type == MEDIA_TYPE_IMAGE) {
				mediaFile = new File(mediaStorageDir.getPath() + File.separator
						+ "IMG_" + timeStamp + ".jpg");
			} else if (type == MEDIA_TYPE_VIDEO) {
				mediaFile = new File(mediaStorageDir.getPath() + File.separator
						+ "VID_" + timeStamp + ".mp4");
			} else {
				return null;
			}
			return mediaFile;
		}


	/**
	 * Initialise the fragments to be paged
	 */
	private void initialisePaging() {

		List<Fragment> fragments = new Vector<Fragment>();
		fragments.add(Fragment.instantiate(this, ActivityMainPage.class.getName()));
		fragments.add(Fragment.instantiate(this, FacebookMainFragment.class.getName()));
		fragments.add(Fragment.instantiate(this, AboutUsFragment.class.getName()));
		//fragments.add(Fragment.instantiate(this, TestDualFrag.class.getName()));
		this.mPagerAdapter  = new PagerAdapater(super.getSupportFragmentManager(), fragments);

		ViewPager pager = (ViewPager)findViewById(R.id.viewpager);
		pager.setAdapter(this.mPagerAdapter);
	}
    /**
     * This method is called when the sending activity has finished, with the
     * result it supplied.
     */
	
	public String getRealImagePath(Uri uriPath) {

		String[] proj = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uriPath, proj, null, null, null);
		int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

		cursor.moveToFirst();
		String path = cursor.getString(index);
		path = path.substring(5);

		return path;
	}

    
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			Intent i = new Intent(this, ActivityEditImage.class);
			switch (requestCode) {
			case REQ_CODE_TAKE_PICTURE:
				// Gets the file name
				lastImgSelectedName = imgUri.getLastPathSegment();
				System.out.println(lastImgSelectedName);
				V.Log("Taken with camera",
						imgUri.getLastPathSegment());
				V.Log("IMG DIRECTORY LOCATION", imgUri.getPath());
				i.putExtra(V.TAKEN_PICTURE, true);
				i.putExtra(V.IMAGE_PATH, imgUri.getPath());
				i.putExtra(V.IMAGE_FILE, lastImgSelectedName);
				startActivity(i);
				imageSource = IMG_SOURCE_CAMERA;
				break;
			case REQ_CODE_PICK_PICTURE:
				imgUri = data.getData();
				// Whole pathName
				galleryDir = "/mnt/" + getRealImagePath(imgUri);
				// Gets the file name
				lastImgSelectedName = galleryDir.substring(
						galleryDir.lastIndexOf("/") + 1, galleryDir.length());

				i.putExtra(V.TAKEN_PICTURE, false);
				i.putExtra(V.IMAGE_PATH, galleryDir);
				i.putExtra(V.IMAGE_FILE, lastImgSelectedName);
				startActivity(i);

				// Just the path, does not include filename
				galleryDir = galleryDir.substring(0,
						galleryDir.lastIndexOf("/") + 1);
				imageSource = IMG_SOURCE_GALLERY;

				break;
			case V.REQ_CODE_PICK_PICTURE_FB:
				Bundle bundle = data.getExtras();
				Bitmap image = (Bitmap) bundle.get("image");
				i.putExtra(V.TAKEN_PICTURE, false);
				i.putExtra(V.IMAGE_PATH, bundle.getString("imgUrl"));
				i.putExtra(V.IMAGE_FILE, lastImgSelectedName);
				startActivity(i);
				break;
			
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
    public static class ReceiveResultFragment extends Fragment {
        // Definition of the one requestCode we use for receiving resuls.
        static final private int GET_CODE = 0;

        private TextView mResults;

        private OnClickListener mGetListener = new OnClickListener() {
            public void onClick(View v) {
                // Start the activity whose result we want to retrieve.  The
                // result will come back with request code GET_CODE.
            	
                Intent intent = new Intent(getActivity(), FacebookSSOActivity.class);
                startActivityForResult(intent, GET_CODE);
            }
            

        };

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        }

        @Override
        public void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.main_menu, container, false);

            return v;
        }



    }
}